package com.yanqu.road.server.handle;

import com.yanqu.road.NettyMgr;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.game.message.SequentialMessageExecuter;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.CrossReqMgr;
import com.yanqu.road.server.manger.SequentialMessageExecuterMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.connect.ServerConnectionGroup;
import com.yanqu.road.connect.ServerLinkControl;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.task.GameCommandTask;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

@Sharable
public class GameServerHandler extends SimpleChannelInboundHandler<YanQuMessage> {

	private static Logger logger = LogManager.getLogger(GameServerHandler.class.getName());


	public GameServerHandler() {
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, YanQuMessage msg) throws Exception {
		int code = msg.getCode();
		if (code == GameProtocol.S_DA_FU_WENG_CROSS_UNION_COLLECT_RESULT) {
			CrossReqMgr.receiveMsg(msg);
		} else if (SequentialMessageExecuterMgr.isSequentialMessage(code)) {
			SequentialMessageExecuter messageExecuter = SequentialMessageExecuterMgr.getSequentialMessageExecuter(code);
			GameCommandTask gameCommandTask = new GameCommandTask(ctx, msg, messageExecuter);
			if(null != messageExecuter){
				messageExecuter.addCommandTask(gameCommandTask);
			}else {
				GameServer.getServerCommandExecutor().execute(gameCommandTask);
			}
		} else{
			long playerId = msg.getPlayerId();
			GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(playerId);
			GameCommandTask gameCommandTask = new GameCommandTask(ctx, msg, gamePlayer);
			if (gamePlayer != null) {
				if (gamePlayer.getCommandStatistics().isWaitKick(msg.getCode())) {
					return;
				}
				if (gamePlayer.getCommandStatistics().monitoringCmdSecondTimes(msg.getCode())) {
					//发邮件
					//踢下线
					GamePlayerMgr.kickAndSendMailBySecondCmdMonitor(gamePlayer, msg.getCode());
					return;
				}
				//已登录玩家，加到玩家消息执行队列
				gamePlayer.addCommandTask(gameCommandTask);
			} else {
				//未登录玩家，直接到线程池执行
				GameServer.getServerCommandExecutor().execute(gameCommandTask);
			}
		}
	}


	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		logger.error(" address {} 连接异常:" , ctx.channel().remoteAddress() , cause);
		ServerConnectionGroup serverSessionGroup = ctx.channel().attr(NettyMgr.LINKED_CLIENT).get();
		if (serverSessionGroup != null) {
			ServerLinkControl.removeLinkedClient(ctx);
			logger.error("连接异常, ip地址: {}", ctx.channel().remoteAddress());
		}
		ctx.close();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		logger.info("连接断开, ip地址:" + ctx.channel().remoteAddress());
		ServerConnectionGroup serverSessionGroup = ctx.channel().attr(NettyMgr.LINKED_CLIENT).get();
		if (serverSessionGroup != null) {
			ServerLinkControl.removeLinkedClient(ctx);
			logger.error("连接异常, ip地址: {}", ctx.channel().remoteAddress());
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("收到链接, ip地址: {}" ,ctx.channel().remoteAddress());
	}


}
